package cn.itcast.consumer.controller;

import cn.itcast.consumer.domain.Goods;
import cn.itcast.consumer.feign.GoodsFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/order")
@RefreshScope   //开启config刷新功能
public class OrderController {
//    @Autowired
//    RestTemplate restTemplate;

//    @Autowired
//    DiscoveryClient discoveryClient;

    @Autowired
    GoodsFeign goodsFeign;

    @Value("${itcast}")
    String itcast;

    @GetMapping("/add/{id}")
    public Goods add(@PathVariable("id") int goodsId) {
        //远程调用
//        String url="http://127.0.0.1:8000/goods/findById/"+goodsId;
        //获取服务方队列
//        List<ServiceInstance> instances = discoveryClient.getInstances("EUREKA-PROVIDER");
//        if (instances == null) {
//            return null;
//        }
//        //取一个服务
//        ServiceInstance serviceInstance = instances.get(0);
////        //地址
////        String host = serviceInstance.getHost();
////        //端口
////        int port = serviceInstance.getPort();
////        System.out.println(host+"---"+port);
////        String url = "http://" + host + ":"+ port + "/goods/findById/" + goodsId;
//        //直接获取uri
//        URI uri = serviceInstance.getUri();
//        System.out.println(uri);
//        String url = uri + "/goods/findById/" + goodsId;

//        String url ="http://EUREKA-PROVIDER/goods/findById/" + goodsId;
//        //restTemplate远程访问的一种模板
//        ResponseEntity<Goods> forEntity = restTemplate.getForEntity(url, Goods.class);
//        Goods goods = forEntity.getBody();


        Goods goods = this.goodsFeign.findById(goodsId);
        goods.setTitle(goods.getTitle()+"+++"+itcast);
        return goods;
    }
}
